using Microsoft.AspNetCore.Mvc;
using KnowledgeQA.Data;
using Microsoft.EntityFrameworkCore;

namespace KnowledgeQA.API.Controllers
{
    /// <summary>
    /// 健康检查控制器
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class HealthController : ControllerBase
    {
        private readonly KnowledgeQADbContext _context;
        private readonly ILogger<HealthController> _logger;

        public HealthController(KnowledgeQADbContext context, ILogger<HealthController> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 获取系统健康状态
        /// </summary>
        /// <returns>系统状态信息</returns>
        [HttpGet]
        public async Task<IActionResult> GetHealth()
        {
            try
            {
                var healthInfo = new
                {
                    Status = "Healthy",
                    Timestamp = DateTime.UtcNow,
                    Version = "1.0.0",
                    Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production",
                    Database = await CheckDatabaseHealth(),
                    Services = new
                    {
                        API = "Running",
                        Swagger = "Available at /swagger",
                        Database = "SQLite"
                    }
                };

                return Ok(healthInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "健康检查失败");
                return StatusCode(500, new
                {
                    Status = "Unhealthy",
                    Timestamp = DateTime.UtcNow,
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 检查数据库连接状态
        /// </summary>
        /// <returns>数据库状态</returns>
        private async Task<string> CheckDatabaseHealth()
        {
            try
            {
                await _context.Database.CanConnectAsync();
                return "Connected";
            }
            catch
            {
                return "Disconnected";
            }
        }
    }
} 